from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.models import News, Category, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu

@profile_blu.route('/other_news_list')
def other_news_list():
    p = request.args.get('p',1)
    user_id = request.args.get('user_id')
    try:
        p = int(p)
    except Exception as  e:
        current_app.logger.error(e)
        p = 1

    if not all([p,user_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')

    try :
        user = User.query.get(user_id)
    except Exception as  e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg='数据查询错误')

    if not user :
        return jsonify(errno = RET.NODATA,errmsg = '没有该用户')

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p,constants.OTHER_NEWS_PAGE_MAX_COUNT,False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据查询错误')

    news_dict_li= []
    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())

    data = {
        'current_page':current_page,
        'total_page':total_page,
        'news_list':news_dict_li
    }
    return jsonify(errno = RET.OK,errmsg = 'ok',data = data)

@profile_blu.route('/other_info')
@user_login_data
def other_info():
    user_id = request.args.get('id')
    if not user_id:
        abort(404)
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not other:
        abort(404)

    is_followed = False
    if g.user:
        if other.followers.filter(User.id == g.user.id).count()>0:
            is_followed=True
    user = g.user

    data = {
        'user_info':user.to_dict() if user else None,
        'other_info':other.to_dict(),
        'is_followed':is_followed
    }

    return render_template('news/other.html',data = data)

@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    p = request.args.get('p')
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user
    if not user:
        return redirect('/')
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate =user.followed.paginate(p,constants.USER_FOLLOWED_MAX_COUNT,False)
        follows = paginate.items
        total_page =paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []



    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {"user":user_dict_li,'current_page':current_page,'total_page':total_page}

    return render_template('news/user_follow.html',data = data)


@profile_blu.route('/pass_info',methods = ['POST','GET'])
@user_login_data
def pass_info():

    user = g.user
    if  not user:
        return redirect('/')

    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    params = request.json
    old_password = params.get('old_password')
    new_password = params.get('new_password')

    if not all([old_password,new_password]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')

    if not user.check_password(old_password):
        return jsonify(errno = RET.PARAMERR,errmsg = '原密码不正确')

    user.password = new_password

    return jsonify(errno = RET.OK,errmsg = '保存成功')




@profile_blu.route('/pic_info',methods = ['POST','GET'])
@user_login_data
def pic_info():
    user = g.user
    if not user :
        return redirect('/')

    if request.method =='GET':
        return render_template('news/user_pic_info.html', data={'user_info': user.to_dict()})

    try:
        avatar_url = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '读取文件出错')

    try:
        key = storage(avatar_url)
    except Exception as  e:
        current_app.logger.error(e)
        return jsonify(errno = RET.THIRDERR,errmsg = '上传文件出错')

    user.avatar_url = key
    try:
        db.session.commit()
    except Exception as  e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '保存用户数据失败')

    return jsonify(errno = RET.OK,errmsg = 'OK', data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/news_release',methods = ['POST','GET'])
@user_login_data
def news_release():
    user = g.user
    if not user:
        return redirect('/')
    if request.method == 'GET':

        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        categories_dict = []
        for category in categories:
            categories_dict.append(category.to_dict())

        categories_dict.pop(0)
        return render_template('news/user_news_release.html',data = {'categories':categories_dict})

    title = request.form.get('title')
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get('index_image')
    category_id = request.form.get('category_id')
    source = '个人发布'

    if not all([title,digest,content,index_image,category_id,source]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')

    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数有误')
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg = '图片上传失败')

    news = News()
    news.title = title
    news.digest = digest
    news.category_id = category_id
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX+key
    news.user_id = user.id
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '数据上传失败')

    return jsonify(errno = RET.OK,errmsg = '发布成功,等待审核' )


@profile_blu.route('/news_list')
@user_login_data
def  news_list():

    if not g.user:
        return redirect('/')

    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e :
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news_items in news_li:
        news_dict_li.append(news_items.to_dict())

    data = {'news_list':news_dict_li,'current_page':current_page,'total_page':total_page}

    return render_template('news/user_news_list.html',data = data)



@profile_blu.route('/user_collection')
@user_login_data
def user_collection():
    p = request.args.get('p',1)

    try:
        p = int(p)
    except Exception as e :
        current_app.logger.error(e)
        p = 1

    user = g.user
    collections = []
    current_page = 1
    total_page = 1

    try:
        paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    collection_dict_li = []

    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {'total_page':total_page,'current_page':current_page,'collections':collection_dict_li}

    return render_template('news/user_collection.html',data = data)

@profile_blu.route('/info')
@user_login_data
def get_user_info():
    user = g.user
    if not user:
        return redirect('/')

    data = {
        'user_info':user.to_dict()
    }
    return render_template('news/user.html',data = data)

@profile_blu.route('/user_info',methods = ['POST','GET'])
@user_login_data
def base_info():

    user = g.user
    if not user:
        return redirect('/')


    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={'user_info':user.to_dict()})

    params = request.json
    nick_name = params.get('nick_name')
    gender = params.get('gender')
    signature = params.get('signature')
    if not all([nick_name,gender,signature]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')

    if gender not in (['MAN','WOMAN']):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '数据保存失败')

    session['nick_name'] = nick_name

    return jsonify(errno = RET.OK,errmsg = '更新成功')



